<template>
  <div class="right-info">
    <div class="info-header">
      <span>信息</span>
    </div>
    <div class="info-content">
      <!-- 检查所见文本框 -->
      <div class="text-section">
        <label class="section-label">检查所见</label>
        <div class="observation-display" v-html="formattedObservation" @click="handleObservationClick"></div>
      </div>
      
      <!-- 检查结论文本框 -->
      <div class="text-section">
        <label class="section-label">检查结论</label>
        <el-input
          v-model="checkConclusion"
          type="textarea"
          :rows="10"
          placeholder="请输入检查结论..."
          class="text-area"
        />
      </div>
    </div>
    
    <!-- 按钮区域 - 固定在底部 -->
    <div class="button-section">
      <el-button type="primary" @click="handleSave">保存</el-button>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="danger" @click="handleClear">清空</el-button>
    </div>
    
    <!-- 下拉框 -->
    <div 
      v-if="showDropdown" 
      class="dropdown-overlay" 
      @click="closeDropdown"
    >
      <div 
        class="dropdown-menu" 
        :style="{ top: dropdownPosition.top + 'px', left: dropdownPosition.left + 'px' }"
        @click.stop
      >
        <div 
          v-for="option in currentOptions" 
          :key="option.value" 
          class="dropdown-item"
          @click="selectOption(option)"
        >
          {{ option.value }}
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, nextTick } from 'vue'
import { ElMessage } from 'element-plus'

/**
 * 右侧信息面板组件 - 显示检查所见和检查结论
 */

// 响应式数据
const checkObservation = ref('')
const checkConclusion = ref('')
const showDropdown = ref(false)
const dropdownPosition = ref({ top: 0, left: 0 })
const currentOptions = ref([])
const currentItemId = ref('')
const currentNodeId = ref('')
const currentClickedHTML = ref('')

// 格式化检查所见文本
const formattedObservation = computed(() => {
  if (!checkObservation.value) {
    return '<div class="empty-placeholder">暂无检查所见信息</div>'
  }
  
  let formatted = checkObservation.value
    // 处理黑体文本（卡片名称）
    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
    // 统一处理可点击选项，保持 data-options-encoded 属性
    .replace(/<span class="clickable-option" data-item-id="(.*?)" data-options='(.*?)'>(.*?)<\/span>/g, 
      '<span class="clickable-option" data-item-id="$1" data-options-encoded="$2">$3</span>')
    // 处理换行
    .replace(/\n/g, '<br>')
  
  return formatted
})

// 按钮事件处理
const handleSave = () => {
  ElMessage.info('调用保存接口')
}

const handleCancel = () => {
  // 取消操作暂不实现具体逻辑
}

const handleClear = () => {
  checkObservation.value = ''
  checkConclusion.value = ''
  ElMessage.success('已清空文本框内容')
}

// 处理观察区域点击事件
const handleObservationClick = (event) => {
  const target = event.target
  if (target.classList.contains('clickable-option')) {
    handleOptionClick(target)
  }
}

// 处理可点击选项
const handleOptionClick = (element) => {
  const itemId = element.getAttribute('data-item-id')
  const nodeId = element.getAttribute('data-node-id')
  // 支持两种属性名（向后兼容）
  const encodedOptions = element.getAttribute('data-options-encoded') || element.getAttribute('data-options')
  
  try {
    // 解码base64编码的选项数据
    const decodedOptionsStr = decodeURIComponent(atob(encodedOptions))
    const options = JSON.parse(decodedOptionsStr)
    
    currentOptions.value = options
    currentItemId.value = itemId
    currentNodeId.value = nodeId
    currentClickedHTML.value = element.outerHTML
    
    // 计算下拉框位置
    const rect = element.getBoundingClientRect()
    dropdownPosition.value = {
      top: rect.bottom + window.scrollY,
      left: rect.left + window.scrollX
    }
    
    showDropdown.value = true
  } catch (error) {
    console.error('解析选项数据失败:', error)
  }
}

// 定义事件发射
const emit = defineEmits(['option-changed'])

// 选择下拉框选项
const selectOption = (option) => {
  // 使用base64编码存储选项数据
  const optionsJson = JSON.stringify(currentOptions.value)
  const encodedOptions = btoa(encodeURIComponent(optionsJson))

  const newSpanHTML = `<span class=\"clickable-option\" data-item-id=\"${currentItemId.value}\" data-node-id=\"${currentNodeId.value || ''}\" data-options-encoded=\"${encodedOptions}\">${option.value}</span>`

  let replaced = false
  if (currentClickedHTML.value) {
    const before = checkObservation.value
    checkObservation.value = checkObservation.value.replace(currentClickedHTML.value, newSpanHTML)
    replaced = before !== checkObservation.value
  }

  // 若未成功（例如 outerHTML 不一致），回退到更精确的正则：限定 nodeId（若存在）
  if (!replaced) {
    const nodeIdPart = currentNodeId.value ? `[^>]*data-node-id=\\\"${currentNodeId.value}\\\"` : ''
    const regex = new RegExp(
      `<span class=\\\"clickable-option\\\"[^>]*data-item-id=\\\"${currentItemId.value}\\\"${nodeIdPart}[^>]*>[^<]*<\\/span>`,
      'g'
    )
    checkObservation.value = checkObservation.value.replace(regex, newSpanHTML)
  }
  
  // 发射事件通知父组件更新表单数据（带上 nodeId 定位卡片）
  emit('option-changed', {
    itemId: currentItemId.value,
    nodeId: currentNodeId.value,
    newValue: option.value
  })
  
  showDropdown.value = false
  ElMessage.success(`已更新选项为：${option.value}`)
}

// 关闭下拉框
const closeDropdown = () => {
  showDropdown.value = false
}

// 暴露方法供父组件调用
defineExpose({
  updateObservation: (text) => {
    checkObservation.value = text
  },
  clearAll: () => {
    handleClear()
  }
})
</script>

<style scoped>
.right-info {
  height: 100%;
  padding: 10px;
  display: flex;
  flex-direction: column;
}

.info-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
  flex-shrink: 0;
}

.info-header span {
  font-weight: bold;
  font-size: 16px;
}

.info-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 15px;
  overflow: hidden;
  padding-bottom: 15px;
}

.text-section {
  display: flex;
  flex-direction: column;
  gap: 8px;
  flex: 1;
  min-height: 200px;
}

/*.resizable-section {
  position: relative;
  resize: vertical;
  overflow: hidden;
}*/

.resize-handle {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: #dcdfe6;
  cursor: ns-resize;
  opacity: 0;
  transition: opacity 0.2s ease;
}

.resizable-section:hover .resize-handle {
  opacity: 1;
}

.section-label {
  font-weight: 500;
  font-size: 14px;
  color: #303133;
  flex-shrink: 0;
}

.text-area {
  flex: 1;
  height: 100%;
}

.text-area :deep(.el-textarea__inner) {
  resize: none;
  font-size: 13px;
  line-height: 1.5;
  height: 100%;
  min-height: 150px;
}

.button-section {
  display: flex;
  justify-content: center;
  gap: 12px;
  padding: 15px 0;
  border-top: 1px solid #ebeef5;
  flex-shrink: 0;
  position: sticky;
  bottom: 0;
  background: #fff;
  z-index: 10;
}

.button-section .el-button {
  min-width: 80px;
}

/* 观察显示区域样式 */
.observation-display {
  flex: 1;
  min-height: 150px;
  padding: 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #fff;
  font-size: 13px;
  line-height: 1.6;
  overflow-y: auto;
}

.empty-placeholder {
  color: #c0c4cc;
  font-style: italic;
  text-align: center;
  padding: 40px 20px;
}

/* 可点击选项样式 */
.observation-display :deep(.clickable-option) {
  color: #409eff;
  cursor: pointer;
  text-decoration: underline;
  transition: all 0.2s ease;
}

.observation-display :deep(.clickable-option:hover) {
  color: #66b1ff;
  background-color: rgba(64, 158, 255, 0.1);
  padding: 2px 4px;
  border-radius: 3px;
}

/* 下拉框样式 */
.dropdown-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 2000;
  background-color: transparent;
}

.dropdown-menu {
  position: absolute;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 2001;
  min-width: 120px;
  max-height: 200px;
  overflow-y: auto;
}

.dropdown-item {
  padding: 8px 12px;
  cursor: pointer;
  font-size: 13px;
  color: #606266;
  transition: background-color 0.2s ease;
}

.dropdown-item:hover {
  background-color: #f5f7fa;
  color: #409eff;
}

.dropdown-item:first-child {
  border-top-left-radius: 4px;
  border-top-right-radius: 4px;
}

.dropdown-item:last-child {
  border-bottom-left-radius: 4px;
  border-bottom-right-radius: 4px;
}
</style>